<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\User as UserModel;
use think\facade\Cookie;
use think\exception\ValidateException;
use think\facade\Session;
use think\Request;

class Auth
{
    protected  $middleware = [//控制器中间件
        \app\middleware\Auth::class => ['only' => ['logout']],
        \app\middleware\Guest::class => ['only' => ['create']],
    ];
    public function create()
    {
        return view('auth/create');
    }

    public function save(Request $request)
    {

        try {

            validate([
                'email|邮箱账号'=>'require|email|max:255|token',
                'password|密码'=>'require|min:6'
            ])->batch()->check($request->post());
            $user = UserModel::where('email',$request->post('email'))->find();

            if($user && $user->password == sha1($request->post('password').getSalt())) {
                    if($user->actived)
                    {
                        $userArr=$user->toArray();
                        $userArr['avatar']=$user->avatar;
                        session('user',$userArr);
                        if($request->post('remember_me')){
                            Cookie::set('user_id',$user->id,86400*30);
                        }
                        return redirect((string)url('User/read', ['id' => $user->id]))->with('success', '欢迎回来~');
                    }
                   else{
                       session('user',null);
                        return redirect((string) url('home'))->with('danger','您的账号还未激活，请先到注册邮箱中点击激活~');
                     }
            }
            else
            {
                Session::flash('old',$request->post());
                return redirect((string) url('login.create'))->with('danger','您的邮箱账号或密码错误~');
            }

        } catch (ValidateException $e) {
            //记录旧的表单输入记录,闪存
            Session::flash('old',$request->post());
            if(!empty($errors=$e->getError()))
            {
                session('errors',$errors);//保存会话信息
                return redirect((string) url('login.create'));
            }


            // 验证失败
        }
    }

    public function logout()
    {
        session('user',null);
        Cookie::delete('user_id');
        return redirect((string) url('login.create'))->with('success','您已成功退出登录~');
    }

}
